/*
* Centralize all xml updates to one place, crap, this code got bigger than the old one...
* We can always extend this with vey little code...
*/
#include "stdinc.h"
#include "DCPlusPlus.h"
#include "UpdateManager.h"
#include "ClientProfileManager.h"
#include "ClientVersionManager.h"
#include "File.h"

void UpdateManager::updateFiles(StringIntMap& aUrls) {
	// < filebyint, addy >
	updatelist = aUrls; 
	for(StringIntIter j = updatelist.begin(); j != updatelist.end(); ++j) {
		dcdebug("Adding %s\n", j->second.c_str());
	}
	startDownload();
}

void UpdateManager::on(HttpConnectionListener::Data, HttpConnection*, const u_int8_t* buf, int len) throw() {
	downBuf.append((char*)buf, len); 
}

void UpdateManager::on(HttpConnectionListener::Complete, HttpConnection*, const string&/* aLine*/) throw() {
			c.removeListener(this);
			if(!downBuf.empty()) {
				string fname = Util::getAppPath() + "XML\\" + Util::getUpdateFileNames(currentlyUpdating);
				File f(fname + ".tmp", File::WRITE, File::CREATE | File::TRUNCATE);
				f.write(downBuf);
				f.close();
				try {
					File::deleteFile(fname + ".old");
					File::renameFile(fname, fname + ".old");
					File::renameFile(fname + ".tmp", fname);
				} catch(...) {
					File::renameFile(fname + ".tmp", fname);
					dcdebug("UpdateManager::onAction, no old file found but who cares?");
				}
				reloadFile(currentlyUpdating);
				startDownload();
				dcdebug("Completet %s\n", Util::getUpdateFileNames(currentlyUpdating).c_str());
			}
}
void UpdateManager::on(HttpConnectionListener::Failed, HttpConnection*, const string& aLine) throw() {
			c.removeListener(this);
			{
				fire(UpdateManagerListener::FAIL, currentlyUpdating);
				startDownload();
				dcdebug("Failed %s %s\n", Util::getUpdateFileNames(currentlyUpdating).c_str(), aLine);
			}
}

void UpdateManager::startDownload() {
	currentlyUpdating = 0;
	downBuf = Util::emptyString;
	StringIntIter j = updatelist.begin();
	if(	j != updatelist.end()) {
		c.addListener(this);
		c.downloadFile(j->second + Util::getUpdateFileNames(static_cast<int>(j->first)));
		currentlyUpdating = static_cast<int>(j->first);
		updatelist.erase(j->first);
		dcdebug("startDownload %s\n", Util::getUpdateFileNames(currentlyUpdating).c_str());
	}
}

void UpdateManager::reloadFile(int file) {
	switch(file) {
		case CLIENT: 
			ClientProfileManager::getInstance()->reloadClientProfilesFromHttp();	
			break;
		case MYINFO:
			ClientProfileManager::getInstance()->reloadMyinfoProfilesFromHttp();
			break;
		case CLIENTVERSION: 
			ClientVersionManager::getInstance()->getClientVersions(true);
			break;
		case ISP: 
			ClientProfileManager::getInstance()->reloadISPs();
			break;
		default: return;
	}
	dcdebug("UpdateManager::reloadFile %d\n", file);
	fire(UpdateManagerListener::COMPLETE, file);
}
/**
 * @file
 * $Id: UpdateManager.cpp 303 2005-08-18 23:46:43Z sulan $
 */